<template>
  <div class="kafkaConfig">
    <el-divider content-position="left">{{$t('kafka服务器')}}</el-divider>
    <el-form :model="record" :label-width="lang === 'zh'?'110px':'150px'" label-position="left" ref="form" :rules="rules" inline :style="'width:' + (lang === 'zh'?'725px;':'810px;')">
      <el-form-item :label="$t('KAFKA日志外发')" prop="status" style="width:600px;">
        <el-switch id="Kafka-log-status" :width="lang === 'zh'?60:70" v-model="record.status" @change="kafkaConfigStatusChange(record.status)" class="kafkaSwitch switch" active-color="#009966" inactive-color="#CCCCCC" active-value="on" inactive-value="off" :active-text="$t('启用')" :inactive-text="$t('停用')" />
      </el-form-item>
      <el-form-item :label="$t('IP地址')" prop="addr">
        <el-input id="Kafka-log-addr" v-emoji v-model="record.addr" ref="addr" style="width:215px;" size='small'>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('服务端端口')" prop="port" style="margin-left:50px;">
        <el-input id="Kafka-log-port" v-emoji v-model="record.port" ref="port" style="width:215px;" size='small'>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('加密方式')" prop="mechanism" style="width:600px;">
        <el-radio-group v-model="record.mechanism">
          <el-radio id="Kafka-log-normal" label="normal" class="normal">{{$t('无')}}</el-radio>
          <el-radio id="Kafka-log-ssl" label="ssl" class="ssl">SSL</el-radio>
          <el-radio id="Kafka-log-ssl_sasl" label="ssl_sasl" class="ssl_sasl">SASL+SSL</el-radio>
          <el-radio id="Kafka-log-ssl_kerberos" label="ssl_kerberos" class="ssl_kerberos">Kerberos+SSL</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="record.mechanism === 'ssl_kerberos'">
        <el-form-item :label="$t('krb用户名')" prop="krbname">
          <el-input id="Kafka-log-krbname" v-emoji v-model="record.krbname" ref="krbname" key="krbname" style="width:215px;" size='small'>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('服务名')" prop="service" style="margin-left:50px;">
          <el-input id="Kafka-log-service" v-emoji v-model="record.service" ref="service" key="service" style="width:215px;" size='small'>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('krb密钥文件')" prop="keytab" style="width:600px;">
          <el-button id="Kafka-log-krbDialog" size="small" @click="krbDialog" class="krbDialog">{{ record.keytab ? $t('已配置'):$t('未配置') }}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
        </el-form-item>
      </div>
      <div v-if="record.mechanism === 'ssl_sasl'">
        <el-form-item :label="$t('用户名')" prop="name" style="width:600px;">
          <el-input id="Kafka-log-name" v-emoji v-model="record.name" ref="name" key="name" style="width:215px;" size='small'>
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('密码')" prop="password" style="width:600px;">
          <el-input id="Kafka-log-password" v-emoji v-model="record.password" ref="password" key="password" style="width:215px;" size='small'>
          </el-input>
        </el-form-item>
      </div>
      <el-form-item :label="$t('SSL证书配置')" prop="cafile" style="width:600px;" v-if="record.mechanism !== 'normal'">
        <el-button id="Kafka-log-sslDialog" size="small" @click="sslDialog" class="sslDialog">{{record.cafile ? $t('已配置'):$t('未配置')}}<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      </el-form-item>
      <el-form-item :label="$t('压缩方式')" prop="type" style="width:600px;">
        <el-select v-model="record.type" ref="type" :placeholder="$t('请选择')" size='small'>
          <el-option v-for="(item,index) in typeList" :key="item.value" :label="item.label" :value="item.value" :id="`Kafka-log-type-${item.value}`">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('日志等级')" prop="lv" style="width:600px;">
        <el-select v-model="record.lv" ref="lv" :placeholder="$t('请选择')" size='small'>
          <el-option v-for="item in lvList" :key="item.value" :label="item.label" :value="item.value" :id="`Kafka-log-lv-${item.value}`">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('日志格式')" prop="format" style="width:600px;">
        <el-select v-model="record.format" ref="format" placeholder="请选择" size='small'>
          <el-option v-for="item in formatList" :key="item.value" :label="item.label" :value="item.value" :id="`Kafka-log-format-${item.value}`">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Topic" prop="topic" style="width:600px;">
        <el-input id="Kafka-log-topic" v-emoji v-model="record.topic" ref="topic" style="width:215px;" size='small'>
        </el-input>
      </el-form-item>
    </el-form>
    <div>
      <el-button id="Kafka-log-logSave" type="success" @click="logSave" class="logSave">{{$t('应用配置')}}</el-button>
      <el-button id="Kafka-log-clearConfig" type="danger" @click="clearConfig" class="clearConfig">{{$t('清空配置')}}</el-button>
    </div>
    <pre id="jsonShow" v-show="jsonShow"></pre>
    <upload-file-ca v-if="uploadFileCaDialogVisible" ref="refUploadFileCaDialogVisible" @caFileChange='caFileChangeCa'></upload-file-ca>
    <upload-file-krb v-if="uploadFileKrbDialogVisible" ref="refUploadFileKrbDialogVisible" @caFileChange='caFileChangeKrb'></upload-file-krb>
  </div>
</template>
<script>
import { getKafkaLogConfig, kafkaSwitch, setKafkaConfig, cleanKafkaLogConfig } from '@/api/system/kafkaLogConfig'
import uploadFileCa from './components/uploadFileCa'
import uploadFileKrb from './components/uploadFileKrb'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  name: 'LoginConfig',
  components: {
    uploadFileCa,
    uploadFileKrb
  },
  data () {
    var validatePort = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (isNaN(Number(value))) {
        callback(new Error(this.$t('只能输入数字')))
      } else if (Number(value) < 1 || Number(value) > 65535) {
        callback(new Error(this.$t('端口范围为1-65535')))
      } else {
        callback()
      }
    }
    var validateAddr = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validateTopic = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    return {
      uploadFileCaDialogVisible: false,
      uploadFileKrbDialogVisible: false,
      lang: this.$i18n.locale,
      formData: new FormData(),
      record: {
        status: 'off',
        addr: '',
        port: '',
        mechanism: 'normal',
        lv: 1,
        type: 'none',
        topic: '',
        cafile: '',
        certfile: '',
        keyfile: '',
        name: '',
        password: '',
        krbname: '',
        keytab: '',
        service: '',
        format:'json'
      },
      recordCopy: {
        status: 'off',
        addr: '',
        port: '',
        mechanism: 'normal',
        lv: 1,
        type: 'none',
        topic: '',
        cafile: '',
        certfile: '',
        keyfile: '',
        name: '',
        password: '',
        krbname: '',
        keytab: '',
        service: '',
        format:'json'
      },
      lvList: [
        {value: 1, label: 'ERROR'},
        {value: 2, label: 'ALERT'},
        {value: 3, label: 'INFO'},
        {value: 4, label: 'DEBUG'},
      ],
      formatList:[
        {
        value: 'json', label: 'json'
        },
        {
        value: 'syslog', label: 'syslog'
        }
      ],
      typeList: [
        {value: 'none', label: 'none'},
        {value: 'gzip', label: 'gzip'},
        {value: 'snappy', label: 'snappy'}
      ],
      fileList: {
        'cafile': 'server.cer.pem',
        'certfile': 'client.cer.pem',
        'keyfile': 'client.key.pem',
        'keytab': 'client.keytab'
      },
      stateList: {
        'on': 'start',
        'off': 'stop'
      },
      jsonShow: false,
      rules: {
        addr: [{ required: false, trigger: 'blur', validator: validateAddr }],
        port: [{ required: false, trigger: 'blur', validator: validatePort }],
        topic: [{ required: false, trigger: 'blur', validator: validateTopic }]
      }
    }
  },
  computed: {
    change () {
      const { mechanism } = this.record
      return { mechanism }
    }
  },
  watch: {
    change: {
      handler (newValue) {
        if (newValue.mechanism === 'ssl_sasl') {
          this.$nextTick(() => {
            const data = ['name', 'password']
            inputClass(this.$refs, data)
          })
        } else if (newValue.mechanism === 'ssl_kerberos') {
          this.$nextTick(() => {
            const data = ['krbname', 'service']
            inputClass(this.$refs, data)
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted () {
    this.listData()
    this.$nextTick(() => {
      const data = ['addr', 'port', 'topic']
      const selectData = ['type', 'lv','format']
      inputClass(this.$refs, data)
      selectClass(this.$refs, selectData)
    })
  },
  methods: {
    listData () {
      getKafkaLogConfig().then(res => {
        if (res.status === 0) {
          this.record = Object.assign(this.record, res.info[0])
        }
      })
    },
    kafkaConfigStatusChange (status) {
      kafkaSwitch({ state: this.stateList[status] }).then(res => {
        this.jsonShow = false
      }).catch(e => {
        this.record.status = status === 'on' ? 'off' : 'on'
        this.jsonShow = true
        document.getElementById('jsonShow').innerHTML = ''
        document.getElementById('jsonShow').innerHTML = e.message // json为要展示到页面的数据
      })
    },
    logSave () {
      this.$refs.form.validate(valid => {
        if (valid) {
          let formData = new FormData()
          for (let item in this.record) {
            if (!Object.is(this.record[item], null) && !Object.is(this.record[item], '')) {
              if (this.record[item] === '已配置') {
                formData.append(item, this.fileList[item])
              } else {
                formData.append(item, this.record[item])
              }
            }
          }
          for (let item of this.formData.entries()) {
            if (!Object.is(item[1], null) && !Object.is(item[1], '') && !Object.is(item[1], 'null')) {
              formData.append(item[0], item[1])
            }
          }
          setKafkaConfig(formData).then(res => {
            this.$message({
              message: this.$t('保存成功'),
              type: 'success'
            })
          })
        }
      })
    },
    sslDialog () {
      this.uploadFileCaDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refUploadFileCaDialogVisible.init(this.record)
      })
    },
    krbDialog () {
      this.uploadFileKrbDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refUploadFileKrbDialogVisible.init(this.record)
      })
    },
    clearConfig () {
      this.$confirm(this.$t('您是否要清空配置?'), this.$t('提示'), {
        closeOnClickModal: false,
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        confirmButtonClass: 'confirmButton',
        cancelButtonClass: 'confirmCancelButton',
        type: 'warning'
      }).then(() => {
        cleanKafkaLogConfig().then(res => {
          if (res.status === 0) {
            this.$messages.success(this.$t(res.msg))
            this.record = Object.assign({}, this.recordCopy)
            this.listData()
            this.$nextTick(() => {
              this.$refs['form'].clearValidate()
            })
          }
        })
      })
    },
    caFileChangeCa (data, formData) {
      this.record.cafile = data.cafile
      this.formData.set('cafile', formData.get('cafile'))
      this.record.certfile = data.certfile
      this.formData.set('certfile', formData.get('certfile'))
      this.record.keyfile = data.keyfile
      this.formData.set('keyfile', formData.get('keyfile'))
    },
    caFileChangeKrb (data, formData) {
      this.record.keytab = data.keytab
      this.formData.set('keytab', formData.get('keytab'))
    }
  }
}
</script>
<style lang="less" scoped>
.kafkaConfig {
  max-width: 810px;
  margin: 0 auto;
  padding-top: 1px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .el-divider__text {
    font-size: 18px;
    font-weight: 600;
  }
  .el-divider {
    margin: 40px 0 30px;
  }
}
pre {
  width: 100%;
  min-height: 200px;
  outline: 1px solid #ccc;
  text-align: left;
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>
